import React, { useEffect, useState } from "react";
import { Checkbox, Flex, NavBar, Button } from "antd-mobile";
import {
    FormOutlined,
    DeleteOutlined,
    PlusOutlined,
    EditOutlined,
} from "@ant-design/icons";
import axios from "axios";
import MineNavBar from "../../components/MineNavBar";
import "./list.css";

const AddressList = ({ history }) => {
    /**
     * 第一个参数：list 就是组件内的一个 state
     * 第二个参数：setList 就相当于 class 组件中的 setState()
     */
    const [list, setList] = useState([]);

    /**
     * 分页
     */
    const [pagenum, setPagenum] = useState(1);
    const [pagesize, setPagesize] = useState(3);
    const [total, setTotal] = useState(0);

    /**
     * 相当于 class 组件的 componentDidMount()
     * 第二个参数：当数组内的变量发生变化时，这个 useEffect 会重新执行一次。
     * 也就是说，如果数组内没有变量，那么就只会在组件加载时，执行一次
     */
    useEffect(async () => {
        // 请求头
        // axios.defaults.headers.uid = JSON.parse(
        //     window.sessionStorage.getItem("user")
        // ).id;
        axios.defaults.headers.token = window.sessionStorage.getItem("token");
        // 发送请求
        const res = await axios.get("/addresses", {
            params: { pagesize, pagenum },
        });
        // 分页总数
        setTotal(res.data.data.total);
        setList(res.data.data.list);
    }, []);

    const onDefaultAddressChange = async (e, item) => {
        const is_default = e.target.checked ? 1 : 0;

        const res = await axios.put(`/addresses/${item.id}/default`, {
            is_default,
        });

        if (res.data.code === 200) {
            list.filter((address) => address.is_default === 1).forEach(
                (item) => (item.is_default = 0)
            );
            item.is_default = is_default;
            setList(list.slice());
        }
    };

    const onLoadMore = async () => {
        const res = await axios.get("/addresses", {
            params: { pagesize, pagenum: pagenum + 1 },
        });
        list.push(...res.data.data.list);
        setList(list);
        setTotal(res.data.data.total);
        setPagenum(pagenum + 1);
    };

    const renderItem = (item) => (
        <div className="list-item" key={item.id}>
            <Flex justify="between">
                <span>{item.username}</span>
                <span>{item.mobile}</span>
            </Flex>

            <p>{item.address}</p>

            <Flex justify="between">
                <div>
                    <Checkbox
                        checked={item.is_default === 1}
                        onChange={(e) => onDefaultAddressChange(e, item)}
                    />
                    <span style={{ marginLeft: "5px" }}>默认地址</span>
                </div>

                <div>
                    <EditOutlined />
                    <span style={{ marginRight: "15px" }}>编辑</span>

                    <span>
                        <DeleteOutlined />
                        删除
                    </span>
                </div>
            </Flex>
        </div>
    );

    return (
        <div className="address-list">
            <NavBar>管理收货地址</NavBar>

            {/* 渲染列表 */}
            {list.map((item) => renderItem(item))}

            {total > list.length && (
                <Button onClick={onLoadMore}>加载更多...</Button>
            )}

            {/* 添加地址 */}
            <Button onClick={() => history.push("/address/add")}>
                <PlusOutlined /> 添加地址
            </Button>
        </div>
    );
};

export default AddressList;
